<script setup>
import { ref, onMounted } from 'vue';
import { getGoodsAPI, updateProductAPI, addProductAPI, deleteProductAPI, uploadImgAPI } from '../../../api/goods';
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
let pagenum = ref(1); // 修改为从第1页开始
let pageSize = ref(5);
let total = ref(0);
let dialogFormVisible = ref(false);
let tableData = ref([]);
let addGoods = ref(false);
let fileList = ref([]); // 文件列表
let dialogVisible = ref(false); // 预览对话框
let dialogImageUrl = ref(''); // 预览图片URL
const formRef = ref(null);
const addFormRef = ref(null);
let deleat = ref(false);
// 添加商品表单数据
const addG = ref({
    product_name: "",
    money: "",
    operation: "",
    brand: "",
})
// 编辑商品表单数据
const form = ref({
    id: "",
    product_name: "",
    money: "",
    brand: "",
    logo_url: "",
    operation: ""
});
// 定义表单标签宽度
const formLabelWidth = '120px';
//添加商品表单校验规则
const rules = {
    product_name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 120, message: '长度在 2 到 20 个字符', trigger: 'blur' },
        { pattern: /^[^\s]+$/, message: '名称不能包含空格', trigger: 'blur' }
    ],
    money: [
        { required: true, message: '请输入金额', trigger: 'blur' },
        { pattern: /^[1-9]\d*(\.\d{1,2})?$/, message: '请输入有效的数字（1-9开头，最多两位小数）', trigger: 'blur' },
    ],
    brand: [
        { required: true, message: '请输入品牌名称', trigger: 'blur' },
        { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
    ],
    operation: [
        { required: true, message: '请输入描述信息', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
    ],
    // logo_url: [
    //     { required: true, message: '请上传品牌LOGO', trigger: 'change' }
    //     // 移除URL格式验证，因为我们直接上传文件而不是URL
    // ]
}
// 获取商品数据
const getArr = async () => {
    try {
        // 详细记录当前页码和每页大小
        console.log('开始获取数据:', { 当前页码: pagenum.value, 每页大小: pageSize.value });
        // 调用API获取数据
        let res = await getGoodsAPI(pagenum.value, pageSize.value);
        console.log('API响应:', res);

        // 安全地处理响应数据
        if (res && res.data) {
            tableData.value = res.data.items || [];
            // 优先使用API返回的total值，确保分页准确性
            total.value = res.data.total !== undefined ? res.data.total : tableData.value.length;
        } else {
            tableData.value = [];
            total.value = 0;
            console.warn('API返回数据格式不符合预期');
        }

        console.log('表格数据:', tableData.value);
    } catch (error) {
        console.error('获取数据失败:', error);
        tableData.value = []; // 错误时清空数据避免显示旧数据
        total.value = 0;
    }
}

const handleSizeChange = (newSize) => {
    console.log('切换每页大小:', { 新大小: newSize });
    pageSize.value = newSize;
    getArr();
}

const handleCurrentChange = (newPage) => {
    console.log('切换页码:', { 新页码: newPage });
    pagenum.value = newPage;
    getArr();
}

onMounted(() => {
    getArr();
});
//取消
const quiao = () => {
    // 重置表单和关闭对话框
    if (formRef.value) {
        formRef.value.resetFields();
    }
    if (addFormRef.value) {
        addFormRef.value.resetFields();
    }
    dialogFormVisible.value = false;
    addGoods.value = false;
}
const bianji = (id) => {
    dialogFormVisible.value = true;
    // 清空文件列表
    fileList.value = [];
    console.log('编辑索引:', id);
    // 将id转换为数值类型进行查找
    const numericId = Number(id);
    console.log('转换后的数值ID:', numericId);

    // 使用转换后的数值ID查找项目
    const item = tableData.value.find(item => Number(item.id) === numericId);

    if (item) {
        form.value.id = numericId; // 保存数值类型的ID
        form.value.product_name = item.product_name;
        form.value.money = item.money;
        form.value.operation = item.operation;
        form.value.brand = item.brand;
        form.value.logo_url = item.logo_url || '';
        
        console.log('填充表单数据:', form.value);
    }
}
//添加商品
const add = async () => {
    // 重置表单后打开对话框
    if (addFormRef.value) {
        addFormRef.value.resetFields();
    }
    // 清空ID，确保是添加操作
    addG.value.id = "";
    addGoods.value = true;

}

const addGood = async () => {
    try {
        // 验证表单
        await addFormRef.value.validate();

        let logoUrl = ''; // 存储上传后的图片URL

        // 1. 先上传图片（如果有）
        const newFile = fileList.value.find(file => file.raw);
        if (newFile && newFile.raw) {
            console.log('上传文件:', newFile.raw);

            // 创建图片上传的 FormData
            imgFormData = new FormData();
            imgFormData.append('file', newFile.raw);

            // 调用图片上传接口
            const uploadRes = await uploadImgAPI(imgFormData);
            console.log('图片上传结果:', uploadRes);

            if (uploadRes.code === 200){
                logoUrl = uploadRes.data.data
                console.log('图片URL:', logoUrl)
            }
        }

        // 2. 准备商品数据（包含图片URL）
        const productData = {
            product_name: addG.value.product_name,
            money: addG.value.money, // 转为数字
            brand: addG.value.brand,
            operation: addG.value.operation,
            logo_url: logoUrl // 添加图片URL
        };
        // 3. 调用商品添加接口 - 这里是关键，确保调用正确的API
        const res = await addProductAPI(productData);
        console.log('添加结果:', res);

        // 重置表单和关闭对话框
        addFormRef.value.resetFields();
        addGoods.value = false;
        fileList.value = []; // 清空文件列表 

        getArr(); // 刷新列表

    } catch (error) {
        // 如果是验证失败，不显示错误日志
        if (error.name !== 'ValidateError') {
            console.error('添加失败:', error);
        }
    }
}

// 自定义上传处理函数 - 用于element plus的上传组件
const handleUpload = async (options) => {
  try {
    console.log('开始上传文件:', options.file);
    
    // 创建FormData
    const formData = new FormData();
    formData.append('file', options.file);
    
    // 调用上传API
    const res = await uploadImgAPI(formData);
    
    if (res && res.code === 200) {
      // 上传成功
      console.log('文件上传成功:', res);
      // 设置预览URL
      options.file.url = res.data?.url || '';
      // 调用success回调
      options.onSuccess?.(res);
      
      // 更新表单的logo_url字段
      if (addGoods.value) {
        addG.value.logo_url = res.data?.url || '';
      } else {
        form.value.logo_url = res.data?.url || '';
      }
    } else {
      // 上传失败
      console.error('文件上传失败:', res);
      options.onError?.(new Error('上传失败'));
    }
  } catch (error) {
    console.error('上传异常:', error);
    options.onError?.(error);
  }
}

// 文件删除处理函数
const handleRemove = (uploadFile, uploadFiles) => {
  // 清空logo_url字段，确保表单验证能正确提示需要重新上传
  if (addGoods.value) {
    addG.value.logo_url = '';
  } else {
    form.value.logo_url = '';
  }
  
  // 如果是本地预览URL，清理它以避免内存泄漏
  if (uploadFile.url && uploadFile.url.startsWith('blob:')) {
    URL.revokeObjectURL(uploadFile.url);
  }
  
  // 从fileList中移除文件，确保不再引用File对象
  fileList.value = fileList.value.filter(item => {
    // 对于当前要移除的文件，确保不再引用其raw属性
    if (item.uid === uploadFile.uid && item.raw) {
      item.raw = null;
    }
    return item.uid !== uploadFile.uid;
  });
  
  ElMessage.info('已删除图片');
}

// 查看图片预览
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
}

// 删除商品
const open = (id) => {
    ElMessageBox.alert('确定要删除此嘛', '商品删除', {
        cfirmButtonText: '确认',
        showCancelButton: '取消',
      type: 'warning',
    }).then(async () => {
        deleteProductAPI(id).then(() => {
          ElMessage.success('删除成功')
            getArr()
        })
    }).catch(() => {
        ElMessage.info('已取消删除')
    });
}

</script>

<template>
        <div>
            <el-card style="max-width: 100% ;margin: 20px;">
                <el-button type="primary" size="small" @click="add">添加</el-button>
                <el-table :data="tableData" style="width: 100%" border>
                <el-table-column prop="id" label="序号" width="80" align="center"/>
                <el-table-column prop="product_name" label="品牌名称" width="180" align="center"/>
                <el-table-column prop="money" label="品牌名称" width="180" align="center"/>
                 <el-table-column prop="operation" label="描述" width="180" align="center"/>
                 <el-table-column prop="brand" label="品牌" width="180" align="center"/>
                <el-table-column label="品牌logo" align="center">
                    <template #default="scope">
                        <img v-if="scope.row.logo_url || scope.row.logo" :src="scope.row.logo_url || scope.row.logo" style="width: 80px; height: 80px; object-fit: contain;" :alt="scope.row.product_name || scope.row.name" />
                        <span v-else>无图片</span>
                    </template>
                </el-table-column>
                <el-table-column label="品牌操作" align="center">
                    <template #default="scope">
                        <el-button type="primary" size="small" style="margin-right: 5px;" @click="bianji(scope.row.id)">编辑</el-button>
                        <el-button type="danger" size="small" @click="open(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
                </el-table>
                <el-pagination
                  v-model:current-page="pagenum"
                  v-model:page-size="pageSize"
                  :total="total"
                  layout="prev, pager, next, jumper, total"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
            </el-card>
        </div>
        <!-- 修改商品 -->
        <el-dialog v-model="dialogFormVisible" title="修改品牌信息" width="500" >
            <el-form ref="formRef" :model="form" :rules="rules">
            <el-form-item label="修改名字" :label-width="formLabelWidth" prop="product_name">
                <el-input v-model="form.product_name" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="修改金额" :label-width="formLabelWidth" prop="money">
                <el-input v-model="form.money" autocomplete="off" />
            </el-form-item>
            <el-form-item label="修改描述信息" :label-width="formLabelWidth" prop="operation">
                <el-input v-model="form.operation" autocomplete="off" />
            </el-form-item>
            <el-form-item label="修改品牌" :label-width="formLabelWidth" prop="brand">
                <el-input v-model="form.brand" autocomplete="off" />
            </el-form-item>
            </el-form>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="quiao">取消</el-button>
                <el-button type="primary" @click="qua">
                确认
                </el-button>
            </div>
            </template>
        </el-dialog>
        <!-- 添加商品 -->
         <el-dialog v-model="addGoods" title="添加品牌信息" width="500" >
            <el-form ref="addFormRef" :model="addG" :rules="rules">
            <el-form-item label="商品名字" :label-width="formLabelWidth" prop="product_name">
                <el-input v-model="addG.product_name" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="品牌名字" :label-width="formLabelWidth" prop="brand">
                <el-input v-model="addG.brand" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="金额" :label-width="formLabelWidth" prop="money">
                <el-input v-model="addG.money" autocomplete="off" />
            </el-form-item>
            <el-form-item label="描述" :label-width="formLabelWidth" prop="operation">
                <el-input v-model="addG.operation" autocomplete="off" />
            </el-form-item>
            <el-form-item label="添加LOGO" :label-width="formLabelWidth" prop="logo_url" >
          <el-upload
                v-model:file-list="fileList"
                :http-request="handleUpload"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <el-dialog v-model="dialogVisible">
                <img :src="dialogImageUrl" alt="Preview Image" style="width: 100%;" />
            </el-dialog>
            </el-form-item>
            </el-form>
            <template #footer>
            <div class="dialog-footer">
                <el-button @click="quiao">取消</el-button>
                <el-button type="primary" @click="addGood">
                确认
                </el-button>
            </div>
            </template>
        </el-dialog>
        <!-- 删除商品 -->
         
</template>

<style scoped></style>
